package com.yyplatform.admin.platform.config.service.impl;

import java.util.List;

import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import com.yyplatform.admin.platform.config.model.dto.SysConfigDTO;
import com.yyplatform.admin.platform.config.model.dto.SysConfigFormDTO;
import com.yyplatform.admin.platform.config.model.dto.SysConfigQueryDTO;
import com.yyplatform.admin.platform.config.model.entity.SysConfigEntity;
import com.yyplatform.admin.platform.config.repository.SysConfigRepository;
import com.yyplatform.admin.platform.config.service.SysConfigService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author sleepforests@163.com
 * <p>
 * Created on 2024/9/21 20:25
 */
@Service
@Slf4j
@AllArgsConstructor
public class SysConfigServiceImpl implements SysConfigService {

    private SysConfigRepository sysConfigRepository;
    private ModelMapper modelMapper;

    @Override
    public void delete(Long id) {
        sysConfigRepository.deleteById(id);
    }

    @Override
    public void update(SysConfigFormDTO sysConfigFormDTO) {

        SysConfigEntity old = sysConfigRepository.getReferenceById(sysConfigFormDTO.getId());
        old.setValue(sysConfigFormDTO.getValue());
        old.setRemark(sysConfigFormDTO.getRemark());

        sysConfigRepository.save(old);
    }

    @Override
    public void save(SysConfigFormDTO sysDeptFormDTO) {
        SysConfigEntity entity = modelMapper.map(sysDeptFormDTO, SysConfigEntity.class);
        sysConfigRepository.save(entity);
    }

    @Override
    public SysConfigDTO get(Long id) {
        SysConfigEntity entity = sysConfigRepository.getReferenceById(id);
        return modelMapper.map(entity, SysConfigDTO.class);
    }

    @Override
    public Page<SysConfigDTO> query(SysConfigQueryDTO pageQueryDTO) {
        Page<SysConfigEntity> entityPage =
                sysConfigRepository.findPage(
                        pageQueryDTO.getCode(),
                        pageQueryDTO.getPageRequestOrderByIdDesc());

        List<SysConfigDTO> list = entityPage.stream()
                .map(e -> modelMapper.map(e, SysConfigDTO.class))
                .toList();

        return new PageImpl<>(list, entityPage.getPageable(), entityPage.getTotalElements());
    }
}
